﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.IO;
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    private XmlDocument xmlDoc;
    /// <summary>
    /// 调入XML
    /// </summary>
    private void LoadXml(string file)
    {
        xmlDoc = new XmlDocument();
        if (File.Exists(Server.MapPath(file)))
        {
            xmlDoc.Load(Server.MapPath(file));
        }
        else
        {
            XmlWriter xwriter = XmlWriter.Create(Server.MapPath(file));
            xwriter.WriteStartDocument(true);
            //写入根元素
            xwriter.WriteStartElement("guestbook");
            xwriter.WriteEndElement();
            xwriter.WriteEndDocument();
           
            xwriter.Close();
            xmlDoc.Load(Server.MapPath(file));
        }
    } 
    /// <summary>
    /// 保存内容
    /// </summary>
    /// <param name="file"></param>
    /// <param name="name"></param>
    /// <param name="add"></param>
    /// <param name="tel"></param>
    /// <param name="content"></param>
    private  bool Save(string file,string name,string add,string tel,string content)
    {
        try
        {
            LoadXml(file);

            XmlNode xmldocSelect = xmlDoc.SelectSingleNode("guestbook");
            XmlElement message = xmlDoc.CreateElement("mesage");
            message.SetAttribute("id",DateTime.Now.ToString("yyyyMMddHHmmssffff"));
            XmlElement uname = xmlDoc.CreateElement("name"); //添加name节点 
            uname.InnerText = name;
            XmlElement uadd = xmlDoc.CreateElement("add"); //添加地址节点
            uadd.InnerText = add;

            XmlElement utel = xmlDoc.CreateElement("tel");
            utel.InnerText = tel;
            XmlElement ucontent = xmlDoc.CreateElement("content");
            ucontent.InnerText = content;
            message.AppendChild(uname);
            message.AppendChild(uadd);
            message.AppendChild(utel);
            message.AppendChild(ucontent);
            xmldocSelect.AppendChild(message);
            xmlDoc.Save(Server.MapPath("guestbook.xml"));
            return true;
        }
        catch(Exception ex)
        {
            Response.Write(ex.Message);
        }
        return false;


    } 
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (Save("guestbook.xml", name.Text, add.Text, tel.Text, content.Text))
        {
            Response.Write("提交成功");
            name.Text = "";
            add.Text = "";
            tel.Text = "";
            content.Text = "";
        }
        else
            Response.Write("提交失败");

			
    }
}
